package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"os"
	"strings"
	"strconv"
)

type Point struct {
	Lon string `json:"Lon"`
	Lat string `json:"Lat"`
}
type Point2 struct {
	PP []Point
}

var (
	golablindex uint64 = 1
	bEmpty      []byte = []byte{}
	lineBreak   string = "\n"
	filename    string = "C:\\Users\\Administrator\\Desktop\\gpspoint.txt"
	singlePoint string = `,{\"Lon\":116131562,\"Lat\":43249995}`
)

func WriteLine(info string) error {
	var (
		file *os.File
		err  error
	)
	file, err = os.OpenFile(filename, os.O_WRONLY|os.O_EXCL|os.O_CREATE, 0755)
	if err != nil {
		file, err = os.OpenFile(filename, os.O_WRONLY|os.O_APPEND, 0755)
		if err != nil {
			fmt.Println("error 4 reason:", err.Error())
			return err
		}
	}
	_, err = file.WriteString(info + lineBreak)
	if err != nil {
		fmt.Println("error 5 reason:", err.Error())
		return err
	}
	return nil
}

func readLine(name string) {
	type Point struct {
		Lon int `json:Lon`
		Lat int `json:Lat`
	}
	type Result struct {
		Rings []Point `json:Rings`
	}
	file, err := os.Open(name)
	if err != nil {
		fmt.Println("error,reason:", err.Error())
		return
	}
	defer file.Close()

	var index int = 1300

	for {
		if index == 0 {
			break
		}
		line := make([]byte, 1024)
		for {
			b := make([]byte, 1)
			_, err := file.Read(b)
			if err == io.EOF {
				break
			}
			if err != nil {
				fmt.Println("error2,reason:", err.Error())
				break
			}
			if string(b) == lineBreak {
				break
			}
			for _, v := range b {
				line = append(line, v)
			}
		}

		if bytes.Index(line, []byte("Rings")) == -1 {
			continue
		}
		line = bytes.TrimSpace(line)
		if bytes.Equal(line, bEmpty) {
			continue
		}

		strline := string(bytes.Trim(line, ","))

		token := "{\"Rings" + strings.Split(strline, "Rings")[1]
		//fmt.Println("token:", token)
		index = index - 1
		result := &Result{}
		err := json.Unmarshal([]byte(token), &result)
		if err != nil {
			fmt.Println("error3,reason:", err.Error())
			return
		}
		//writepairsize := 200
		go func() {
			for _, v := range result.Rings {
				//if writepairsize <= 0 {
				//	break
				//}
				fmt.Println("index:", golablindex, "Lon:", v.Lon, ",Lat:", v.Lat)
				stmp := strconv.Itoa(v.Lon) + "," + strconv.Itoa(v.Lat)
				WriteLine(stmp)
				golablindex = golablindex + 1
				//writepairsize--
			}
		}()
	}
	return
}
func main() {
	readLine("C:\\Users\\Administrator\\Desktop\\Regions.json")
	fmt.Println("finished")
}
